#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 19-6-26 上午9:52
# @Author  : Tom
# @Site    :
# @File    : brands.pyurls.py
# @Software: PyCharm
from django.conf import settings
# from fdfs_client.client import Fdfs_client
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from goods.models import SKUImage, SKU
from meiduo_admin.serilizers import SKUImageSerilizer, SkuSerializer_image
from meiduo_admin.utils import PageNumber_User
from meiduo_mall.utils.response_code import RETCODE


class SKUImageView(ModelViewSet):
    serializer_class = SKUImageSerilizer
    queryset = SKUImage.objects.all()
    pagination_class = PageNumber_User
    permission_classes = [IsAdminUser]

    def SKUImagesView(self, request):
        sku = SKU.objects.all()
        ser = SkuSerializer_image(sku, many=True)
        return Response(ser.data)

    def create(self, request, *args, **kwargs):
        # 1. 获取图片和sku
        image = request.FILES.get("image")
        sku = request.data.get('sku')
        # 2. 创建fastdfs客户端对象。然后上传图片，提取路径
        fdfs = Fdfs_client(settings.FDFS_PATH)
        answer = fdfs.upload_appender_by_buffer(image.read())
        if answer['Status'] != 'Upload successed.':
            return Response({"code": RETCODE.DBERR, "errmsg": "图片保存错误！"})
        path = answer['Remote file_id']
        # 3.保存到数据库
        sku_image = SKUImage.objects.create(sku_id=sku, image=path)
        ser = SKUImageSerilizer(sku_image)
        # 4.返回前端保存对象
        return Response(ser.data, status=201)

    def update(self, request, *args, **kwargs):
        # 1. 获取图片和sku
        image = request.FILES.get("image")
        sku = request.data.get('sku')
        # 2. 创建fastdfs客户端对象。然后上传图片，提取路径
        fdfs = Fdfs_client(settings.FDFS_PATH)
        answer = fdfs.upload_appender_by_buffer(image.read())
        if answer['Status'] != 'Upload successed.':
            return Response({"code": RETCODE.DBERR, "errmsg": "图片保存错误！"})
        path = answer['Remote file_id']
        # 3.保存到数据库
        sku_image = self.get_object()
        sku_image.sku_id = sku
        sku_image.image = path
        sku_image.save()
        ser = SKUImageSerilizer(sku_image)
        # 4.返回前端保存对象
        return Response(ser.data, status=201)
